<?php


namespace app\user\service;


use app\libs\tool\CacheTool;
use app\libs\tool\JwtAuth;
use think\facade\Cache;

class LoginService
{
    /**
     * @throws \app\libs\exception\ServerError
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function save_return_jwt($id)
    {
        $jwtAuth = new JwtAuth(
            config('secure.jwt_alg'),
            config('secure.verify_salt')
        );

        $jwt = $jwtAuth->create(
            ['user_id' => $id],
            config('secure.jwt_nbf'),
            config('secure.jwt_exp')
        );
        $this->setCacheJwt($id, $jwt);

        (new CacheTool())->setCache(config('secure.current_user_key'), $id, config('secure.jwt_exp'));

        return $jwt;
    }

    protected function setCacheJwt($id, $jwt)
    {
        Cache::store('redis')->set(
            config('secure.jwt_token_key'), $jwt, config('secure.jwt_exp')
        );
    }
}